package com.doraro.platform.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JsonUtil {
    @Autowired
    private ObjectMapper objectMapper;

    public void writeJson(HttpServletResponse httpResponse, Result responses) {
        setHeader(httpResponse);
        try {
            String json = objectMapper.writeValueAsString(responses);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    private void setHeader(HttpServletResponse httpResponse) {
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
    }
}
